import React, { Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Card,
  Form,
  Divider,
  Popconfirm,
  Tag,
  message,
  Col,
  Row,
  DatePicker,
  TimePicker,
  Input,
  Select,
  Button,
  Modal,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import AuthorizedButton from '@/components/AuthorizedButton';
import ReissueProductForm from './component/ReissueProductForm';

import styles from '../../styles/Manage.less';

const FormItem = Form.Item;
const { Option } = Select;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

// 日期
const currentDay = moment(new Date(new Date().getTime()));

@Form.create()
@connect(({ marketProduct, loading }) => ({
  marketProduct,
  loading: loading.models.marketProduct,
}))
class ProductManage extends React.Component {
  state = {
    cityId: '-1',
    cities: [],
    triggerTime: '',
    date: currentDay, //
    cityProductId: '',
    productNo: '',
    productName: '',
    dateString: currentDay.format('YYYY-MM-DD'),
    modalVisible: false,
  };

  // 表格字段
  columns = [
    {
      title: '日期',
      width: 160,
      fixed: 'left',
      align: 'center',
      render: (text, record) => <span>{record.date}</span>,
    },
    { title: '城市', width: 120, dataIndex: 'cityId' },
    { title: '仓库', width: 120, dataIndex: 'warehouseId' },
    { title: '商品ID', width: 120, dataIndex: 'cityProductId' },
    { title: '商品编码', width: 120, dataIndex: 'productNo' },
    { title: '商品名称', width: 120, dataIndex: 'productName' },
    {
      title: '价格类型',
      width: 120,
      dataIndex: 'priceType',
      render: text => (text === 1 ? <Tag color="green">折扣</Tag> : <Tag color="cyan">金额</Tag>),
    },
    { title: '价格', width: 120, dataIndex: 'price' },
    { title: '库存', dataIndex: 'inventorySize' },
    { title: '限购', width: 120, dataIndex: 'restrictionSize' },
    {
      title: '活动类型',
      width: 120,
      dataIndex: 'activityType',
      render: text =>
        !text || text === 0 ? <Tag color="blue">限时抢购</Tag> : <Tag color="cyan">新人专享</Tag>,
    },
    {
      title: '状态',
      width: 120,
      dataIndex: 'failType',
      render: text => {
        if (text === 0) return <Tag color="#108ee9">抢购中</Tag>;
        if (text === 1) return <Tag color="#2db7f5">已在活动中</Tag>;
        if (text === 2) return <Tag color="#2de7f5">已加入其他活动</Tag>;
        if (text === 3) return <Tag color="#a70">商品不存在</Tag>;
        if (text === 4) return <Tag color="#e70">库存不足</Tag>;
        if (text === 5) return <Tag color="#070">活动不存在</Tag>;
        if (text === 99) return <Tag color="#570">达标下线</Tag>;
        return <Tag color="#f50">未知</Tag>;
      },
    },
    {
      title: '创建时间',
      width: 100,
      dataIndex: 'created',
      render: text => <span>{moment.unix(text).format('HH:mm')}</span>,
    },
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      width: 90,
      dataIndex: 'option',
      render: (text, record) => (
        <Fragment>
          <AuthorizedButton mask={['DEL']}>
            <Popconfirm
              placement="top"
              title="确定将该商品从活动中下架？"
              onConfirm={() => this.soldOutProductById(record.id)}
            >
              <a>下架</a>
            </Popconfirm>
          </AuthorizedButton>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.handleSearch();
    this.getCities();
  }

  getCities = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'commonInfo/fetchByClassify',
      payload: {
        classify: 'city',
      },
      callback: data => {
        const list = [];
        data.forEach(item => {
          list.push({
            code: item.code,
            name: item.name,
          });
        });
        this.setState({
          cities: list,
        });
      },
    });
  };

  getQueryParams = () => {
    const { dateString, cityId, triggerTime, cityProductId, productNo, productName } = this.state;
    const params = {};
    if (cityId !== '-1') {
      params.cityId = cityId;
    }
    if (triggerTime !== '') {
      params.triggerTime = triggerTime;
    }
    if (dateString) {
      params.date = dateString;
    }
    if (cityProductId !== '') {
      params.cityProductId = cityProductId;
    }
    if (productNo !== '') {
      params.productNo = productNo;
    }
    if (productName !== '') {
      params.productName = productName;
    }
    return params;
  };

  // 查询操作
  handleSearch = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParams();
    dispatch({
      type: 'marketProduct/fetch',
      payload: {
        params,
      },
      callback: () => {},
    });
  };

  // 补发抢购商品
  sendProducts = params => {
    const { dispatch } = this.props;
    dispatch({
      type: 'marketProduct/sendProducts',
      payload: {
        ...params,
      },
      callback: () => {
        this.setState({
          modalVisible: false,
        });
        this.handleSearch();
      },
    });
  };

  // 将指定商品从活动中下架
  soldOutProductById = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'marketProduct/doSoldOutProductById',
      payload: {
        id,
      },
      callback: () => {
        this.handleSearch();
      },
    });
  };

  // 分页、过滤、排序处理
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const queryParams = this.getQueryParams();

    const params = {
      ...formValues,
      ...filters,
      ...queryParams,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'marketProduct/fetch',
      payload: {
        params,
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },
    });
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      marketProduct: { data },
    } = this.props;
    const { date, cityId, cities, modalVisible } = this.state;

    let totalWidth = 0;
    this.columns.forEach(col => {
      const { width } = col;
      if (width) {
        totalWidth += width;
      }
    });

    return (
      <PageHeaderWrapper title="限时抢购商品" content="该商品只表示已成功发送到MGR的商品列表">
        <Card bordered={false}>
          <div className={styles.Manage}>
            <div className={styles.ManageForm}>
              <Form layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={8} sm={24}>
                    <FormItem key="date" label="日期">
                      {getFieldDecorator('date', {
                        initialValue: date,
                      })(
                        <DatePicker
                          onChange={(dateNew, dateString) => {
                            this.setState(
                              {
                                date: dateNew,
                                dateString,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                          placeholder="选择日期"
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="cityId" label="城市">
                      {getFieldDecorator('cityId', {
                        initialValue: cityId,
                      })(
                        <Select
                          key="cityId"
                          placeholder="请选择城市"
                          showSearch
                          optionFilterProp="children"
                          onChange={value => {
                            this.setState(
                              {
                                cityId: value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        >
                          {cities.map(item => (
                            <Option key={item.code} value={item.code}>
                              {item.name}({item.code})
                            </Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="triggerTime" label="触发时间">
                      {getFieldDecorator('triggerTime', {})(
                        <TimePicker
                          onChange={(time, timeString) => {
                            this.setState(
                              {
                                triggerTime: timeString,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                          format="HH:mm"
                          placeholder="选择时间"
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="cityProductId" label="商品ID">
                      {getFieldDecorator('cityProductId', {})(
                        <Input
                          placeholder="请输入"
                          onChange={e => {
                            this.setState(
                              {
                                cityProductId: e.target.value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="productNo" label="商品编号">
                      {getFieldDecorator('productNo', {})(
                        <Input
                          placeholder="请输入"
                          onChange={e => {
                            this.setState(
                              {
                                productNo: e.target.value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="productName" label="商品名称">
                      {getFieldDecorator('productName', {})(
                        <Input
                          placeholder="请输入"
                          onChange={e => {
                            this.setState(
                              {
                                productName: e.target.value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </div>
            <div style={{ float: 'right', paddingBottom: '5px' }}>
              <AuthorizedButton mask={['ADD']}>
                <Button
                  type="primary"
                  onClick={() => {
                    this.setState({
                      modalVisible: true,
                    });
                  }}
                >
                  补发限时抢购商品
                </Button>
                &nbsp;&nbsp;
                <Button
                  onClick={() => {
                    const { dispatch } = this.props;
                    Modal.confirm({
                      title: '询问',
                      content: '确定下架销售进度达标商品么？',
                      okText: '确定',
                      cancelText: '再想想',
                      onOk: () => {
                        dispatch({
                          type: 'marketProduct/doSoldOutCheck',
                          payload: {},
                          callback: () => {
                            message.success('下架达标商品成功');
                          },
                        });
                      },
                    });
                  }}
                >
                  下架达标商品
                </Button>
              </AuthorizedButton>
            </div>
            <Divider type="horizontal" />
            <StandardTable
              loading={loading}
              data={data}
              scroll={{ x: totalWidth }}
              columns={this.columns}
              rowKey={record => record.id}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {modalVisible && (
          <ReissueProductForm
            modalVisible={modalVisible}
            handleOpt={this.sendProducts}
            handleModalVisible={() => {
              this.setState({
                modalVisible: false,
              });
            }}
          />
        )}
      </PageHeaderWrapper>
    );
  }
}

export default ProductManage;
